package com.tech.platform.cms.admin.service;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tech.platform.cms.admin.dao.mapper.TenantMapper;
import com.tech.platform.cms.admin.dao.pojo.Tenant;
import com.tech.platform.cms.common.constant.Constant;
import com.tech.platform.cms.common.model.CommonResult;
import com.tech.platform.cms.common.model.PageResult;
import com.tech.platform.cms.common.utils.ValidationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author shengqiang.wu
 * @date 2020/3/24/024 14:38
 * @desc
 */
@Service
@Slf4j
public class TenantService {

    @Autowired
    private TenantMapper tenantMapper;

    public CommonResult<String> addTenant(Tenant tenant){
        try{
            if(ValidationUtil.validateBean(tenant).hasErrors()){
                log.error("[大鱼管理系统] 添加租户,出现错误,参数验证失败:{}", JSONUtil.toJsonPrettyStr(tenant));
                return new CommonResult<>(Constant.PARAM_ERROR,"参数异常");
            }
//            tenant.setSalt(String.valueOf(System.currentTimeMillis()));
            tenant.setCreateTime(new Date());
            tenantMapper.insert(tenant);
            return new CommonResult<>(Constant.SUCCESS,"添加成功");
        }catch (Exception ex){
            log.error("[大鱼管理系统] 添加租户,出现系统异常:{}",ex.getMessage(),ex);
            return new CommonResult<>(Constant.SYSTEM_ERROR,"系统异常");
        }
    }

    public PageResult<List<Tenant>> page(int current, int size, String keyWord) throws Exception{
        try{
            IPage<Tenant> page = new Page<>(current,size);
            QueryWrapper<Tenant> wrapper = new QueryWrapper<>();
            wrapper.like("enterprise_name",keyWord);
            page = tenantMapper.selectPage(page,wrapper);
            return new PageResult<>(Constant.SUCCESS,"success",page.getTotal(),page.getRecords());
        }catch (Exception ex){
            log.error("[大鱼管理系统] 分页查询租户列表,出现系统异常:{}",ex.getMessage(),ex);
            throw new Exception("分页查询异常",ex.getCause());
        }
    }
}
